package services

import (
	"errors"
	"lingc/models"
	"time"

	"gorm.io/gorm"
)

// SysLangService 提供账号登录校验的服务
type SysLangService struct {
	DB *gorm.DB
}

// NewSysLangService 创建一个新的 SysLangService 实例
func NewSysLangService(db *gorm.DB) *SysLangService {
	return &SysLangService{DB: db}
}

//表单业务

/**
 * @Description: 分页获取列表
 * @param where
 * @param page
 * @param pageSize
 * @return []*models.SysLang
 * @return int
 * @return int64
 * @return error
 */
func (s *SysLangService) PageSysLangList(where string, page, pageSize int) ([]*models.SysLangList, int, int64, error) {
	var groups []*models.SysLang
	var total int64

	// 计算偏移量
	offset := (page - 1) * pageSize

	// 获取总记录数
	if err := s.DB.Model(&models.SysLang{}).Where(where).Count(&total).Error; err != nil {
		return nil, 1, 0, err
	}

	// 获取分页数据
	if err := s.DB.Where(where).Offset(offset).Limit(pageSize).Order("id DESC").Find(&groups).Error; err != nil {
		return nil, 1, 0, err
	}
	var list []*models.SysLangList
	list = []*models.SysLangList{}
	for _, data := range groups {
		list = append(list, &models.SysLangList{
			ID:        data.ID,
			Title:     data.Title,
			Name:      data.Name,
			Code:      data.Code,
			LangCode:  data.LangCode,
			IsDefault: data.IsDefault,
			Status:    data.Status,
			AppID:     data.AppID,
			CreatedAt: time.Unix(data.CreatedAt, 0).Format("2006-01-02 15:04:05"), // 格式化时间戳
			UpdatedAt: time.Unix(data.UpdatedAt, 0).Format("2006-01-02 15:04:05"), // 格式化时间戳
		})
	}

	return list, page, total, nil
}

// GetLangList 获取语言列表
func (s *SysLangService) GetLangList() ([]*models.SysLangList, error) {
	var list_data []*models.SysLang
	var list []*models.SysLangList
	list = []*models.SysLangList{}
	if err := s.DB.Where("status = ?", 1).Find(&list_data).Error; err != nil {
		return list, err
	}
	for _, data := range list_data {
		list = append(list, &models.SysLangList{
			ID:       data.ID,
			Title:    data.Title,
			Name:     data.Name,
			Code:     data.Code,
			LangCode: data.LangCode,
		})
	}
	return list, nil

}

/**
 * @Description: 创建新
 * @param username
 * @param password
 * @param realname
 * @param avatar
 * @param status
 * @return *models.SysLangCreate
 * @return error
 */
func (s *SysLangService) CreateSysLang(data *models.SysLangCreate) (*models.SysLangCreate, error) {

	/*
		Title     string `json:"title"`
		Name      string `json:"name"`
		Code      string `json:"code"`
		LangCode  string `json:"lang_code"`
		IsDefault uint8  `json:"is_default"`
		Status    uint8  `json:"status"`
		AppID     int    `json:"app_id"`
	*/
	addData := &models.SysLang{
		Title:     data.Title,
		Name:      data.Name,
		Code:      data.Code,
		LangCode:  data.LangCode,
		IsDefault: data.IsDefault,
		Status:    data.Status,
		AppID:     data.AppID,
		CreatedAt: time.Now().Unix(),
		UpdatedAt: time.Now().Unix(),
	}
	if data.IsDefault == 1 {
		s.DB.Model(&models.SysLang{}).Where("is_default = ?", 1).Update("is_default", 0)
	}
	// 保存到数据库
	if err := s.DB.Create(addData).Error; err != nil {
		return nil, err
	}
	return data, nil
}

// GetSysLang 获取信息
func (s *SysLangService) GetSysLang(where string) (*models.SysLang, error) {
	var data models.SysLang
	if err := s.DB.Where(where).First(&data).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("数据不存在")
		}
		return nil, err
	}
	// log.Printf("data_info:%v", data)
	return &data, nil
}

/**
 * @Description: 更新信息
 * @param data
 * @return error
 */
func (s *SysLangService) UpdateSysLang(data *models.SysLangUpdate) (*models.SysLangUpdate, error) {
	// 检查名是否已存在
	var existingData models.SysLang
	if err := s.DB.Where("id = ?", data.ID).First(&existingData).Error; err != nil {
		return nil, errors.New("数据不存在")
	}
	/*
		Title     string `json:"title"`
		Name      string `json:"name"`
		Code      string `json:"code"`
		LangCode  string `json:"lang_code"`
		IsDefault uint8  `json:"is_default"`
		Status    uint8  `json:"status"`
		AppID     int    `json:"app_id"`
	*/
	existingData.Title = data.Title
	existingData.Name = data.Name
	existingData.Code = data.Code
	existingData.LangCode = data.LangCode
	existingData.IsDefault = data.IsDefault
	existingData.Status = data.Status
	existingData.AppID = data.AppID
	existingData.UpdatedAt = time.Now().Unix()
	if data.IsDefault == 1 {
		s.DB.Model(&models.SysLang{}).Where("is_default = ?", 1).Update("is_default", 0)
	}
	return data, s.DB.Save(existingData).Error
}

/**
 * @Description: 删除
 * @param id
 * @return error
 */
func (s *SysLangService) DeleteSysLang(id uint) error {
	var data models.SysLang
	if err := s.DB.Where("id = ?", id).First(&data).Error; err != nil {
		return errors.New("数据不存在")
	}
	return s.DB.Delete(&data).Error
}

/**
 * @Description: 批量删除
 * @param id
 * @return error
 */
func (s *SysLangService) DeleteSysLangs(ids []string) error {
	for _, id := range ids {
		var data models.SysLang
		if err := s.DB.Where("id = ?", id).First(&data).Error; err != nil {
			return errors.New("数据不存在")
		}
		err := s.DB.Delete(&data).Error
		if err != nil {
			return errors.New("删除失败")
		}
	}
	return nil
}
